package lt.ntec.danblog.server.core;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Injector;

public abstract class CoreController extends HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = -148882796998237659L;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected Injector injector;
    protected final Logger log = Logger.getLogger(this.getClass().getName());

    public CoreController(HttpServletRequest req, HttpServletResponse rsp) {
        super();
        request = req;
        response = rsp;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        log.info("init servlet config called");
        ServletContext context = config.getServletContext();
        injector = (Injector) context.getAttribute(Injector.class.getName());
        if (injector == null) {
            throw new UnavailableException("Guice Injector not found "
                    + "(did you forget to foo koo joo boo?)");
        }
        injector.injectMembers(this);
    }

    public String getParam(int n) {
        String uri = request.getRequestURI();
        String[] parts = uri.split("\\/");
        // TODO hardcoded place for param start
        int part = 3 + n;
        if (part > parts.length - 1) {
            return null;
        }
        return parts[part];
    }

    public abstract void indexAction() throws IOException;
}
